package com.catmai.pssmanager.util;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.swing.JOptionPane;
import javax.swing.JTable;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;


public class JtableToExcel {
	public void transformJtable(JTable table,String tableName)  {
		Workbook book = new HSSFWorkbook();
		Sheet sheet = book.createSheet(tableName);
		Row row1 = sheet.createRow(0);
		int colnum = table.getColumnCount();
		int row = table.getRowCount();
		for (int i = 0; i < colnum; i++) {
            String name = table.getColumnName(i);
            Cell cell = row1.createCell(i);
            cell.setCellValue(name);
        }
		for(int j= 0;j< row;j++) {
			Row row2 = sheet.createRow(j + 1);
		    for(int i = 0;i < colnum; i++) {
		    	try {
		    		row2.createCell(i).setCellValue(table.getValueAt(j, i).toString());	
				} catch (ArrayIndexOutOfBoundsException e) {
					JOptionPane.showMessageDialog(null, "table中有空值");
				}
			}
		}
		try {
			book.write(new FileOutputStream("C:/Users/CatMai/Desktop/" + tableName + ".xls"));
		} catch (FileNotFoundException e1) {
			JOptionPane.showMessageDialog(null, "文件被打开，请关闭重试！");
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		try {
			book.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		JOptionPane.showMessageDialog(null, "文件成功导出！");
	}
}
